package com.workcell.workdata.xthings.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.workcell.workdata.xthings.dao.PartitionDao;
import com.workcell.workdata.xthings.service.PartitionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

@Slf4j
@Service
@RequiredArgsConstructor
public class PartitionServiceImpl implements PartitionService {
    private final PartitionDao partitionDao;

    /**
     * 根据日期创建分区表
     *
     * @param tableName 表名
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createPartitionByDate(String tableName) {
        LocalDate tomorrow = LocalDate.now().plusDays(1);
        String partitionName = "p" + LocalDateTimeUtil.format(tomorrow, DatePattern.PURE_DATE_PATTERN);
        Long count = partitionDao.count(tableName, partitionName);
        if (count != null && count > 0) {
            log.info("表【{}】分区【{}】已存在，无需创建", tableName, partitionName);
            return;
        }

        String level = LocalDateTimeUtil.formatNormal(tomorrow);
        partitionDao.createPartition(tableName, partitionName, level);
        log.info("表【{}】创建分区【{}】",tableName, partitionName);
    }
}
